<?php

include "global.php"; // Get Configuration
getsettings();



error_reporting(5);
####### Checking the website Status ############ //
if ($website_active != '1') {
eval("dooutput(\"".gettemplate("closed_page")."\");");

exit;
}

$records_per_page = 25;
$max_pages = 10;

list($member_id,$email,$sess) = check_session("volunteer");
list($fname,$lname,$title,$company,$industry,$address,$volunteer_details,$volunteer_phone) = $DB_site->query_first("SELECT fname,lname,title,company,industry,address,details,phone FROM volunteers WHERE id='$member_id' AND email='$email'");

if ($_POST["doaction"] == "send_email")
{
  $tid = sql_safe($_POST["tid"]);
  $raw_message = $_POST["message"];
  $email_message = sql_safe($_POST["message"]);
  $other_volunteers = $_POST["other_volunteers"];
  
  $other_volunteers_array = split("\n",$other_volunteers);
  
  if ($tid != "" AND $email_message != "")
  {
    list($teacher_id,$teacher_fname,$teacher_lname,$county_name,$district_name,$school_name,$school_city,$school_zip,$category,$category_name,$months,$best_times,$details,$grades,$students,$subject,$submit_time) = $DB_site->query_first("SELECT
    teacher_id,teacher_fname,teacher_lname,county_name,district_name,school_name,school_city,school_zip,category,category_name,months,best_times,details,grades,students,subject,submit_time FROM tars WHERE id='$tid'");

    list($teacher_email,$school_id) = $DB_site->query_first("SELECT email,school FROM teachers WHERE id='$teacher_id'");
    list($county_name,$district_name,$school_name,$school_address,$school_city,$school_state,$school_zip) = $DB_site->query_first("SELECT county,district,school_name,address,city,state,zip FROM schools WHERE id='$school_id'");
    

    //add badword filtering here
    // Function Call/Usage
    if (filterBadWords($raw_message,"$badWordsFile") == 0) 
    {
        //die("Die with Filter is Clean Text");
    
		srand((double)microtime()*1000000);
		$rand_id = md5(uniqid(rand()));
		$rand_id = addslashes($rand_id);
		$other_volunteers = sql_safe(implode(",",$other_volunteers_array));
        $result = $DB_site->query("INSERT INTO tars_emails (tar_id,teacher_id,county_name,district_name,school_name,school_city,school_zip,subject,grades,students,months,category,category_name,best_times,details,submit_time,email_message,email_status,email_dated,volunteer,rand_id,other_volunteers)
                                        VALUES('$tid','$teacher_id','$county_name','$district_name','$school_name','$school_city','$school_zip','$subject','$grades','$students','$months','$category','$category_name','$best_times','$details','$submit_time','$email_message','pending',now(),'$member_id','$rand_id','$other_volunteers')
                                        ");
        $result = $DB_site->query("UPDATE tars SET email_status='In-Progress' WHERE id='$tid'");
        
        $message = nl2br($raw_message);
		
		// create valid volunteers array
		$valid_volunteers_array = Array();
		foreach ($other_volunteers_array as $other_volunteer)
		{
			$other_volunteer = trim($other_volunteer);
			if ($other_volunteer != "")
			{
				if (check_email_address($other_volunteer))
				{
					array_push($valid_volunteers_array,$other_volunteer);
				}
			}
		}

		// create other volunteer text
		$other_emailed_volunteers = implode("<br>",$valid_volunteers_array);
		if ($other_emailed_volunteers != "") {$other_emailed_volunteers = "Other Volunteers copied for this class:<br>" . $other_emailed_volunteers;}

    	eval("\$message = \"".gettemplate('tar_email_volunteer')."\";");

		// Send email to volunteer
        send_email($do_not_reply_email,$email,"Copy: New Volunteering Request",$message,'text/html');
		
		// send email to other volunteers
		foreach ($valid_volunteers_array as $other_volunteer)
		{
			send_email($do_not_reply_email,$other_volunteer,"Copy: New Volunteering Request",$message,'text/html');
		}
	
		// Send mail to teacher
		send_email($email,$teacher_email,"New Volunteering Request",$message,'text/html');

		//echo "Mail Sent to Teacher: $message<hr>";
		// Write email to file
		if ($fp = fopen("$website_email_path/$rand_id","w"))
		{
			fwrite($fp,$message);
			fclose($fp);
		}
		
        $msg = "<strong>Email sent successfully.</strong><br />";
    } 
    else 
    {
      //die("Die with Filter is NOT Clean Text");
      
      //$result = $DB_site->query("INSERT INTO tars_emails (tar_id,teacher_id,county_name,district_name,school_name,school_city,school_zip,subject,grades,students,months,category,category_name,best_times,details,submit_time,email_message,email_status,email_dated,volunteer)
      //                                VALUES('$tid','$teacher_id','$county_name','$district_name','$school_name','$school_city','$school_zip','$subject','$grades','$students','$months','$category','$category_name','$best_times','$details','$submit_time','$email_message','admin deleted',now(),'$member_id')
      //                                ");
      //$message = nl2br($raw_message);
  		//eval("\$message = \"".gettemplate('tar_email_volunteer')."\";");
  
      //send_email($do_not_reply_email,$email,"Copy: New Volunteering Request",$message,'text/html');
      //send_email($do_not_reply_email,$support_email,"Alert: Bad Word Filter Match ID $member_id - New Volunteering Request",$message,'text/html');
      $msg = "<strong>Inappropriate word(s) detected in the email. Please correct and try again.</strong><br />";
	  $redo_email = 1;
	  $message = $raw_message;
    }

  }
}


if ($_GET["doaction"] == "email" OR $redo_email)
{
  if ($_GET["tid"] != "")
    $tid = $_GET["tid"];
  if ($tid != "")
  {
    list($teacher_id,$teacher_fname,$teacher_lname,$county_name,$district_name,$school_name,$school_city,$school_zip,$category_name,$months,$best_times,$details,$grades,$students) = 
    $DB_site->query_first("SELECT teacher_id,teacher_fname,teacher_lname,county_name,district_name,school_name,school_city,school_zip,category_name,months,best_times,details,
    grades,students FROM tars WHERE id='$tid'");
    list($teacher_email,$school_id) = $DB_site->query_first("SELECT email,school FROM teachers WHERE id='$teacher_id'");
    list($county_name,$district_name,$school_name,$school_address,$school_city,$school_state,$school_zip) = $DB_site->query_first("SELECT county,
    district,school_name,address,city,state,zip FROM schools WHERE id='$school_id'");
    eval("dooutput(\"".gettemplate("volunteers_email")."\");");
    exit;
  }
}

$page = $_GET["page"];
$field_name = trim($_GET["field_name"]);
$field_value = trim($_GET["field_value"]);
$field_value_all = trim($_GET["field_value_all"]);
$sortby = $_GET["sortby"];
$orderby = $_GET["orderby"];

// Process Detailed Search
if ($field_name != '' AND $field_value != '')
{
  $field_names = explode(",",$field_name);
  $field_values = explode(",",$field_value);
  $jump_query = "";
  for ($i = 0; $i < sizeof($field_names); $i++)
  {
    if ($field_names[$i] != "" AND $field_values[$i] != "")
    {
      $name = $field_names[$i];
      $value = urldecode($field_values[$i]);
      $jump_query .= "$name LIKE '%$value%' AND ";
      ${$name . "_option"} = "selected";
	  }
	}
	$jump_query .= "1=1";
	$sort_string .= "field_name=$field_name&field_value=$field_value";
}

// Process Detailed Search
if ($field_name != '' AND $field_value_all != '')
{
  $field_names = explode(",",$field_name);
  $jump_query = "(";
  for ($i = 0; $i < sizeof($field_names); $i++)
  {
    if ($field_names[$i] != "")
    {
      $name = $field_names[$i];
      $value = urldecode($field_value_all);
      $jump_query .= "$name LIKE '%$value%' OR ";
      ${$name . "_option"} = "selected";
	  }
	}
	$jump_query .= "1=0) ";
	$sort_string .= "field_name=$field_name&field_value_all=$field_value_all";
}
//echo $jump_query;

$sort_array = array();
$query_array = array();
if ($sortby == "") {$sortby = "ID";}
if ($orderby == "") {$orderby = "ASC";}
$sort_query = "&sortby=$sortby&orderby=$orderby&";
$sortby = "$sortby $orderby";

if (trim($sort_string) == "") {
	$sort_string = "?";
}
else {
	$sort_string = "?".$sort_string."&";
}

if ($jump_query != '') {$listquery = "WHERE $jump_query AND tar_status='Pending' AND email_status='Open' ";}
else {$listquery = "WHERE tar_status='Pending' AND email_status='Open'  ";}

$field = trim($field);
$text = trim($text);

//echo $listquery;

// Get the Pages
list($total_count) = $DB_site->query_first("SELECT count(*) FROM tars $listquery");
if ($total_count > $records_per_page)
{
	$pages = $total_count/$records_per_page;
	if (gettype($pages) == "double")
	{
		settype($pages,integer);
		$pages++;
	}
  // Show the First Page
	if (!isset($page))
	{
		$page=1;
		$string_pages = ".Top $records_per_page are shown.You can Go directly to PAGES: [";
		$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=1'>&lt;&lt;</a>&nbsp;&nbsp;";

		for($count=1;$count<=$pages;$count++)
		{
		  // Show only max pages
		  if ($count == $max_pages)
		  {
        $string_pages.="...";
        continue;
      }
      if ($count > $max_pages) {continue;}

			if ($count != $page) {
				$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=$count'>";
			}
			$string_pages.="$count&nbsp;&nbsp;";
			if ($count != $page) {
			$string_pages.="</a>";
			}
		}
		$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=2'>&gt;</a>&nbsp;&nbsp;";
		$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=$pages'>&gt;&gt;</a>";
		if (!isset($sortby)) {$sortby = "id ASC";}
		$result = $DB_site->query("SELECT id,county_name,district_name,school_name,school_city,school_zip,category_name,months,best_times,details,grades,students,teacher_id,teacher_fname,teacher_lname,subject,email_status FROM tars $listquery ORDER BY $sortby LIMIT $records_per_page");
		$string_pages.=" ]";
	}
	else // Show the Requested Page
	{
		$string_pages = " You can go directly to PAGES: [";
		$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=1'>&lt;&lt;</a>&nbsp;&nbsp;";
		if ($page > 1) {
			$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=".($page-1)."'>&lt;</a>&nbsp;&nbsp;";
		}

		for($count=1;$count<=$pages;$count++)
		{
		  // Show only max pages on either side of selected page
		  if ( (($page - $count) == $max_pages/2) || (($count - $page) == $max_pages/2) )
		  {
        $string_pages.="...";
        continue;
      }
		  if ( (($page - $count) > $max_pages/2) || (($count - $page) > $max_pages/2) )
		  {
        continue;
      }

			if ($count != $page) {
				$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=$count'>";
			}
			$string_pages.="$count&nbsp;&nbsp;";
			if ($count != $page) {
				$string_pages.="</a>";
			}
		}
		if ($page < $pages) {
			$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=".($page+1)."'>&gt;</a>&nbsp;&nbsp;";
		}
		$string_pages.="<a href='$website_volunteers_overview".$sort_string. $sort_query . "page=$pages'>&gt;&gt;</a> ";
		$start_limit=($page-1)*$records_per_page;
		if (!isset($sortby)) {$sortby = "id ASC";}
		$result = $DB_site->query("SELECT id,county_name,district_name,school_name,school_city,school_zip,category_name,months,best_times,details,grades,students,teacher_id,teacher_fname,teacher_lname,subject,email_status FROM tars $listquery ORDER by $sortby LIMIT $start_limit,$records_per_page");
		$string_pages.=" ]";
	}
}
else
{
	$string_pages = "";
	if (!isset($sortby)) {$sortby = "id ASC";}
	$result = $DB_site->query("SELECT id,county_name,district_name,school_name,school_city,school_zip,category_name,months,best_times,details,grades,students,teacher_id,teacher_fname,teacher_lname,subject,email_status FROM tars $listquery ORDER BY $sortby");
}

$string1 = "";
$count1 = 0;
$color = 0;

// Flip The Order
if ($orderby == "ASC") {$orderby = "DESC";}
elseif ($orderby == "DESC") {$orderby = "ASC";}

if ($total_count == "") $total_count = "0";
$current_subscribers = "";

$current_color = 0;

$current_requests = "";
//$tquery = $DB_site->query("SELECT id,county_name,district_name,school_name,category_name,months,best_times,details,grades,students FROM tars  WHERE ORDER BY ID ASC");
while (list($tid,$county_name,$district_name,$school_name,$school_city,$school_zip,$category_name,$months,$best_times,
$details,$grades,$students,$teacher_id,$teacher_fname,$teacher_lname,$subject,$email_status) = $DB_site->fetch_array($result))
{
	$flag = 1;
	list($school_id,$teacher_email) = $DB_site->query_first("SELECT school,email FROM teachers WHERE id='$teacher_id'");
	list($responses) = $DB_site->query_first("SELECT count(*) FROM tars_emails WHERE tar_id='$tid'");
	list($school_address) = $DB_site->query_first("SELECT address FROM schools WHERE id='$school_id'");
	$best_times = ($best_times == "") ? "-" : $best_times;
	$grades = ($grades == "0") ? "K" : "$grades";
	$current_requests.= "<tr class=\"trclass$current_color\">
						<!--td class=\"results\">$county_name &nbsp;</td-->
						
						<td class=\"results\">$school_name<br /><span class=\"small_text black1\">$school_address</span><br /><span class=\"small_text black1\">$school_city<br />$school_zip</span></td>
						<td class=\"results\">$school_city &nbsp;</td>";
						
	if ($email_status == "Open")
						$current_requests.= "<td class=\"results\">$teacher_lname, $teacher_fname<br />
						<div class=\"volunteer_link\"><a href='map.php?vars=1&tarid=$tid&sess=$sess'>Volunteer</a></div>
						<!--input type=button class=\"volunteer_email_btn\" name=\"volunteer_email_btn\" value=\"Volunteer to visit\" onClick=\"openURL('$website_volunteers_overview?doaction=email&tid=$tid');\"-->
						</td>";
	else
						$current_requests.= "<td class=\"results\"> $teacher_lname, $teacher_fname </td>";
	
	$current_requests.= "<td class=\"results\">$subject</td>
						<td class=\"results\">$category_name</td>
						<td class=\"results\"><span class=\"small_text  strong\">Grade $grades:</span> <span class=\"small_text  black1\">$details</span></td>
						<td class=\"results\">$months<br /><span class=\"small_text  black1\">$best_times</span></td>
						<td class=\"results\">$students</td>
					  </tr>";
	$current_color = ($current_color == "0") ? "1" : "0";
}

$category_dropdown = "<select name='field_value'><option value=''>Select Category</option>";
$cquery = $DB_site->query("SELECT id,category_name FROM categories WHERE is_active='Y' ORDER BY display_order ASC");
while (list($cid,$catname) = $DB_site->fetch_array($cquery))
{
  if ($field_name == "category_name" AND $field_value == $catname)
  {
    $category_dropdown .= "<option value='$catname' selected>$catname</option>";
    $field_value = ""; 
  }
  else
    $category_dropdown .= "<option value='$catname'>$catname</option>";
}
$category_dropdown .= "</select>";

?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <link rel="stylesheet" type="text/css" href="eweek.css" />
        <script src="jquery-1.8.2.js"></script>
	<script src="jquery.ui.core.js"></script>
	<script src="jquery.ui.widget.js"></script>
	<script src="jquery.ui.tabs.js"></script>
        <script> $(document).ready(function() {
        $("#content div").hide(); // Initially hide all content
        $("#tabs li:first").attr("id","current"); // Activate first tab
        $("#content div:first").fadeIn(); // Show first tab content

        $('#tabs a').click(function(e) {
        e.preventDefault();
        $("#content div").hide(); //Hide all content
        $("#tabs li").attr("id",""); //Reset id's
        $(this).parent().attr("id","current"); // Activate this
        $('#' + $(this).attr('title')).fadeIn(); // Show content for current tab
        });
        });
        </script>
    </head>
    <body>
         <?php require("header.php"); ?>
		 <?php require("nav.php");?>       
        <aside>
            <fieldset><legend>Learn More</legend>
                <label><u><a href="http://www.californiatechedresources.org/activitiesonehour.htm">One Hour Activity</a></u></label><br><br> 
                <label>If you would like to speak to K-12 students and teachers about the challenges and rewards of the
engineering, science, or technology professions, please register and you will be able to browse the
teacher requests for classroom visits. </label>
            </fieldset>
            
       
</aside> 
        <section id="mainContent">
           
            Welcome <?php echo ($fname); ?> <?php echo ($lname); ?>
			
            <div id="search">
               <form method=get action="<?php echo($website_volunteers_overview); ?>">
			<input name='field_name' type=hidden value="county_name,school_name,school_city,school_zip,subject,months,details,grades">
            <input name='field_value_all' type=text value="<?php echo($field_value_all);?>">  
                           <input type="submit" value="Search"/>
                    </form>
                    <form>
       
                           <form method=get action="<?php echo($website_volunteers_overview); ?>">
			<input type="hidden" name="field_name" value="category_name">
			<?php echo ($category_dropdown); ?> 
			<input type=submit name='Submit' value='Search'></form> 
                </div>
        <ul id="tabs">
            <li><a href="#" title="tab1">Request List</a>
            
                </li>
        </ul>
   
        <div class="tabcontent">
		 There are <?php echo($total_count); ?> total teacher assistance requests  <?php echo($string_pages); ?>
            <div id="tab1">
                
                <table class="results">
                <thead>
					<tr>
                      <!--th class="legend"><a href="$website_volunteers_overview$sort_string&sortby=county_name&orderby=$orderby">County</a></th-->
<?php
 Echo "<a href=$url>$site_title</a>"
 ?>					  
    <th><?php echo"<a href=$website_volunteers_overview$sort_string&sortby=school_name&orderby=$orderby>School</a>" ?></th>
    <th><?php echo"<a href=$website_volunteers_overview$sort_string&sortby=school_city&orderby=$orderby>City</a>" ?> </th>
    <th><?php echo"<a href=$website_volunteers_overview$sort_string&sortby=teacher_lname&orderby=$orderby>Teacher</a>" ?> </th>
    <th><?php echo"<a href=$website_volunteers_overview$sort_string&sortby=subject&orderby=$orderby>Subject</a>" ?> </th>
    <th><?php echo"<a href=$website_volunteers_overview$sort_string&sortby=category_name&orderby=$orderby>Category</a>" ?></th>
    <th id="details"><?php echo"<a href=$website_volunteers_overview$sort_string&sortby=grades&orderby=$orderby>Details</a>" ?></th>
    <th><?php echo"<a href=$website_volunteers_overview$sort_string&sortby=months&orderby=$orderby>TimeFrame</a>" ?></th>
    <th><?php echo"<a href=$website_volunteers_overview$sort_string&sortby=students&orderby=$orderby>Student #</a>" ?> </th>
                    </tr>
				</thead>
                 <tbody>
					<?php echo($current_requests); ?>
				</tbody>
    
                </table>
       
            </div>
</div>
    </section>
        

    <?php require("footer.php"); ?>
       
        <?php
		
        // put your code here
        ?>
		
		
    </body>
</html>

